(function () {
  'use strict';

  angular
    .module('client')
    .factory('deviceService', deviceService);

  deviceService.$inject = ['$q', '$resource', 'DEVICE_API', 'utilService', 'indexService'];
  function deviceService($q, $resource, DEVICE_API, utilService, indexService) {
    var services = {
      getDeviceInfo: getDeviceInfo,
      setDeviceSize: setDeviceSize,
      applyDevice: applyDevice,
      isAllowApply: isAllowApply,
      setLocalTime: setLocalTime,
      setDeviceModel: setDeviceModel,
      setDeviceInfo: setDeviceInfo,
      round: round,
    };
    return services;

    function getDeviceInfo() {
      var q = $q.defer();
      $resource(DEVICE_API.getDevices)
        .get(
          {},
          function (resp) {
            q.resolve(resp);
          },
          function (resp) {
            q.reject(resp)
          });
      return q.promise;
    }

    function isAllowApply() {
      var q = $q.defer();
      $resource(DEVICE_API.isAllowApply)
        .get(
          {},
          function (resp) {
            q.resolve(resp);
          },
          function (resp) {
            q.reject(resp)
          }
        );
      return q.promise;
    }

    function applyDevice(deviceID, deviceModel, duration, localTime) {
      var q = $q.defer();
      $resource(DEVICE_API.applyDevice, {deviceID: deviceID})
        .save(
          {duration: duration, deviceModel: deviceModel, localTime: localTime},
          function (resp) {
            q.resolve(resp);
          },
          function (resp) {
            q.reject(resp);
          });
      return q.promise;
    }

    function setDeviceSize(w, h) {
      indexService.setDeviceSize(w, h);
    }

    function setLocalTime(localTime, duration) {
        indexService.setLocalTime(utilService.timeConvertToWeb(localTime), duration);
    }

    function setDeviceModel(model) {
      indexService.setDeviceModel(model);
    }

    function setDeviceInfo(opts) {
      indexService.setDeviceInfo(opts);
    }

    function round(num) {
      return Math.round(num);
    }
  }
})();
